package com.qen.encrypt.utils;

import com.alibaba.fastjson2.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * 工具类
 */
public class Utils {

    /**
     * 将JSON内容按照ASCII排序后，组合成a=b&c=d的格式输出
     *
     * @param json
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String sortJsonAndBuildString(JSONObject json) throws UnsupportedEncodingException {
        // 获取所有键名，并按字典顺序（ASCII）排序
        if (json.isEmpty()) {
            return "";
        }
        String[] keys = new String[json.size()];
        int i = 0;
        for (String s : json.keySet()) {
            keys[i] = s;
            i++;
        }
        Arrays.sort(keys);
        StringBuilder result = new StringBuilder();
        for (String key : keys) {
            if (result.length() > 0) {
                result.append("&");
            }
            // 对键和值进行URL编码
            result.append(URLEncoder.encode(key, StandardCharsets.UTF_8.toString()))
                    .append("=")
                    .append(URLEncoder.encode(json.get(key).toString(), StandardCharsets.UTF_8.toString()));
        }
        return result.toString();
    }

}
